using System;
using System.Text;
using System.Web;
using Urs.Core;
using Urs.Data.Domain.Stores;
using Urs.Core.Html;
using Urs.Services.Localization;

namespace Urs.Services.Stores
{
    public partial class GoodsSpecFormatter : IGoodsSpecFormatter
    {
        private readonly IWorkContext _workContext;
        private readonly IGoodsSpecService _goodsSpecService;
        private readonly IGoodsSpecParser _goodsSpecParser;
        private readonly ILocalizationService _localizationService;
        private readonly IWebHelper _webHelper;

        public GoodsSpecFormatter(IWorkContext workContext,
            IGoodsSpecService goodsSpecService,
            IGoodsSpecParser goodsSpecParser,
            ILocalizationService localizationService,
            IWebHelper webHelper)
        {
            this._workContext = workContext;
            this._goodsSpecService = goodsSpecService;
            this._goodsSpecParser = goodsSpecParser;
            this._localizationService = localizationService;
            this._webHelper = webHelper;
        }

        public string FormatAttributes(string attributes, string serapator = ",", bool htmlEncode = true, bool renderPrices = true,
            bool renderGoodsSpecs = true, bool renderGiftCardAttributes = true,
            bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            if (renderGoodsSpecs)
            {
                var pvaCollection = _goodsSpecParser.ParseGoodsSpecs(attributes);
                for (int i = 0; i < pvaCollection.Count; i++)
                {
                    var pva = pvaCollection[i];
                    var valuesStr = _goodsSpecParser.ParseValues(attributes, pva.Id);
                    for (int j = 0; j < valuesStr.Count; j++)
                    {
                        string valueStr = valuesStr[j];
                        string pvaAttribute = string.Empty;
                        if (int.TryParse(valueStr, out int pValueId))
                        {
                            var pvaValue = _goodsSpecService.GetGoodsSpecValueById(pValueId);
                            if (pvaValue != null)
                                pvaAttribute = string.Format("{0}: {1}", pva.GoodsSpecName, pvaValue.Name);
                            
                            if (htmlEncode)
                                pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                        }

                        if (!String.IsNullOrEmpty(pvaAttribute))
                        {
                            if (i != 0 || j != 0)
                                result.Append(serapator);
                            result.Append(pvaAttribute);
                        }
                    }
                }
            }
            return result.ToString();
        }
    }
}
